package com.fangngng.pushall.controller;

import com.fangngng.pushall.constant.ErrorCode;
import com.fangngng.pushall.dto.AddTagVO;
import com.fangngng.pushall.dto.AddTopicVO;
import com.fangngng.pushall.dto.Result;
import com.fangngng.pushall.entity.Tag;
import com.fangngng.pushall.entity.Topic;
import com.fangngng.pushall.entity.User;
import com.fangngng.pushall.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author fei.fang
 * @date 2021/4/9
 **/
@Slf4j
@RestController
public class TagController extends BaseController {

    @Autowired
    private TagService tagService;


    /**
     * 订阅标签
     *
     * @param id
     * @return
     */
    @PreAuthorize("isAuthenticated()")
    @GetMapping(value = "/tag/subscribe/{id}")
    public Result<String> subscribePost(@PathVariable Integer id) {
        User userDetail = super.getCurrentUser();
        if (userDetail == null) {
            log.warn("dashboard需要登录");
            return Result.fail("需要登陆");
        }

        return tagService.subscribeTag(id, userDetail.getEmail());
    }

    /**
     * 添加标签
     *
     * @param addTagVO
     * @return
     */
    @PreAuthorize("isAuthenticated()")
    @PostMapping(value = "/tag/add")
    public Result<Tag> addTag(@RequestBody AddTagVO addTagVO) {
        User userDetail = super.getCurrentUser();
        if (userDetail == null) {
            log.warn("需要登录");
            return new Result<>(ErrorCode.ERROR_PERMISSION_FORBIT);
        }

        if (addTagVO == null || StringUtils.isEmpty(addTagVO.getName())) {
            return new Result<>(ErrorCode.ERROR_PARAM_ERROR);
        }

        return tagService.addTag(addTagVO, userDetail.getEmail());
    }

    /**
     * 查询标签下的主题
     *
     * @param addTagVO
     * @return
     */
    @PostMapping(value = "/tag/topic")
    public Result<List<Topic>> searchTag(@RequestBody AddTagVO addTagVO) {
        if (addTagVO == null || StringUtils.isEmpty(addTagVO.getName())) {
            return new Result<>(ErrorCode.ERROR_PARAM_ERROR);
        }

        List<Topic> topicByTag = tagService.getTopicByTag(addTagVO);
        return Result.ok(topicByTag);
    }
}
